package com.study.living.camera;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.util.AttributeSet;
import android.util.Log;
import android.view.TextureView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class AutoFitTextureView extends TextureView {
    private static final String TAG = "Camera2";

    //宽高比，用double，float精度不够，在转为int时可能会丢掉1
    private double aspectRatio = 0d;

    public AutoFitTextureView(@NonNull Context context) {
        super(context);
    }

    public AutoFitTextureView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoFitTextureView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Sets the aspect ratio for this view. The size of the view will be
     * measured based on the ratio calculated from the parameters.
     *
     * @param width  Camera resolution horizontal size
     * @param height Camera resolution vertical size
     */
    public void setAspectRatio(int width, int height){
        Log.i(TAG, "setAspectRatio: wh=" + width + "-" + height);
        if (width < 0 || height < 0){
            throw new IllegalArgumentException("width and height cannot be negative.");
        }
        this.aspectRatio = width * 1.0d / height;
        SurfaceTexture surfaceTexture = getSurfaceTexture();
        if (surfaceTexture != null){
            //要设置为preview支持的尺寸
            surfaceTexture.setDefaultBufferSize(width, height);
        }
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (aspectRatio == 0f){
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        } else {
            int measuredWidth;
            int measuredHeight;

            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);

            double actualRatio = width > height ? aspectRatio : 1 / aspectRatio;

            // Performs center-crop transformation of the camera frames
            if (width < height * actualRatio){
                measuredWidth = (int) (height * actualRatio);
                measuredHeight = height;
            } else {
                measuredWidth = width;
                measuredHeight = (int) (width / actualRatio);
            }
            Log.i(TAG, "onMeasure: wh=" + measuredWidth + "-" + measuredHeight);
            setMeasuredDimension(measuredWidth, measuredHeight);
        }
    }
}
